//
//  SVGAPlayView.m
//  bliss
//
//  Created by mac on 2023/8/31.
//

#import "SVGAPlayView.h"
#import <Masonry/Masonry.h>

@interface SVGAPlayView ()

@property (strong, nonatomic) SVGAPlayer *player;

@property (strong, nonatomic) SVGAParser *parser;

@end

@implementation SVGAPlayView

- (instancetype)initWithURL:(NSURL *)url {
    self = [super init];
    _player = [[SVGAPlayer alloc] init];
    [self addSubview:_player];
    [_player mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    _player.contentMode = UIViewContentModeScaleAspectFill;
    _player.loops = 1; // 设置循环次数
    _player.delegate = self;
    _parser = [[SVGAParser alloc] init];
    __weak typeof(self) weakSelf = self;
    [weakSelf.parser parseWithURL:url completionBlock:^(SVGAVideoEntity * _Nullable videoItem) {
        
        if(!videoItem.images.count || !videoItem.sprites.count){
            [weakSelf removeFromSuperview];
            return;
        }
        weakSelf.hidden = NO;
        weakSelf.player.videoItem = videoItem;
        [weakSelf.player startAnimation];

    } failureBlock:^(NSError * _Nullable error) {
        NSLog(@"%@",error);
    }];

    return self;
}

- (void)showViewTo:(UIView *)superView {
    [superView addSubview:self];
    self.hidden = YES;
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)layoutSubviews {
}

- (void)svgaPlayerDidAnimatedToPercentage:(CGFloat)percentage {
    if (percentage == 1.0) {
        [self removeFromSuperview];
    }
}

@end
